#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-ataidle
# REQUIRE: LOGIN
# KEYWORD: nojail shutdown

. /etc/rc.subr

ataidle_start()
{
	local IFS="|"
	local f="disk_name disk_hddstandby disk_advpowermgmt disk_acousticlevel"
	eval local $f
	local sf=$(var_to_sf $f)
	local cmd
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT

	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
		"SELECT $sf FROM storage_disk WHERE disk_expiretime IS NULL" | \
	while eval read -r $f; do

		# Run ataidle only in ${disks}
		if [ -n "${disks}" ]; then
			local ok_to_run
			ok_to_run=$(echo "${disks}"| tr " " \\n | while read -r disk_en; do
				if [ "${disk_en}" = "${disk_name}" ]; then
					echo "OK"
					break
				fi
			done)
			if [ -z "${ok_to_run}" ]; then
				continue
			fi
		fi
		case "$disk_name" in
		ad*)
			;;
		da*)
			;;
		*)
			continue
			;;
		esac
		if [ -n "`/usr/local/sbin/smartctl -g apm /dev/${disk_name} | grep Unavailable`" ]; then
		elif [ "${disk_advpowermgmt}" != "Disabled" ]; then
			/sbin/camcontrol apm ${disk_name} -l ${disk_advpowermgmt}
		else
			/sbin/camcontrol apm ${disk_name}
		fi
		if [ "${disk_acousticlevel}" != "Disabled" ]; then
			if [ "${disk_acousticlevel}" = "Minimum" ]; then
				disk_acousticlevel=1
			elif [ "${disk_acousticlevel}" = "Medium" ]; then
				disk_acousticlevel=64
			elif [ "${disk_acousticlevel}" = "Maximum" ]; then
				disk_acousticlevel=127
			fi
		else
			disk_acousticlevel=0
		fi
		if [ -z "`/usr/local/sbin/smartctl -g aam /dev/${disk_name} | grep Unavailable`" ]; then
			/sbin/camcontrol aam ${disk_name} -l ${disk_acousticlevel}
		fi
		if [ "${disk_hddstandby}" != "Always On" ]; then
			# ataidle was in minutes, camcontrol uses seconds.
			disk_hddstandby_cooked=$(expr ${disk_hddstandby} \* 60)
			(sleep 60; /sbin/camcontrol idle ${disk_name} -t ${disk_hddstandby_cooked}) > /dev/null 2>&1 &
		else
			(sleep 60; /sbin/camcontrol idle ${disk_name} -t 0) > /dev/null 2>&1 &
		fi
	done
}

name="ix-ataidle"
rcvar="ataidle_enable"
start_cmd="ataidle_start"
stop_cmd=':'
cmd="${1}"

if [ $# -gt 0 ]; then
	shift
fi
disks=""
if [ -n "$*" ]; then
	disks="$*"
fi

load_rc_config $name
run_rc_command "${cmd}"
